package app.controllers.member;

import app.Const;
import app.models.basic.Msgs;
import app.models.member.Member;
import com.google.common.base.Strings;
import com.jfinal.plugin.activerecord.Page;
import goja.StringPool;
import goja.mvc.Controller;
import goja.security.goja.SecurityKit;
import org.joda.time.DateTime;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2015/3/19.
 */
public class MyMessageController extends Controller {


    public void index() {
        int page = getParaToInt("page", 1);
        final Member member = SecurityKit.getLoginUser(getRequest());
        List<Msgs> msg = Msgs.dao.findByMemberAndThreeMouth(member.getNumber(StringPool.PK_COLUMN).intValue(), page);

        int total = Msgs.dao.findCountByMemberAndThreeMouth(member.getNumber(StringPool.PK_COLUMN).intValue());
        int totalPage;
        if(total%10!=0){
            totalPage = total/10+1;
        }else{
            totalPage = total/10;
        }
        Page<Msgs> msgs = new Page<Msgs>(msg,page,10,totalPage,total);
        setAttr("count",total);
        setAttr("unread",Msgs.dao.findUnReadCountByMemberAndThreeMonth(member.getNumber(StringPool.PK_COLUMN).intValue()));
        setAttr("page",page);
        setAttr("message", msgs);
    }

    public void lookup() {
        Msgs msgs = Msgs.dao.findById(getPara("mid"));
        Map<String, String> result = new HashMap<String, String>();
        result.put("title", msgs.get("title") + "");
        result.put("content", msgs.get("content") + "");
        if (msgs.get(Const.FIELD_STATUS).toString().equals("0")) {
            msgs.set("read_time", DateTime.now());
            msgs.set(Const.FIELD_STATUS, 1);
            msgs.update();
            renderJson(result);
        } else {
            renderJson(result);
        }
    }

    public void read() {
        String mids = getPara("mid");
        String[] smid = mids.split(",");
        if(!Strings.isNullOrEmpty(mids)){
            for (String mid : smid) {
                Msgs msgs = Msgs.dao.findById(mid);
                if (msgs.get(Const.FIELD_STATUS).toString().equals("0")) {
                    msgs.set("read_time", DateTime.now());
                    msgs.set(Const.FIELD_STATUS, 1);
                    msgs.update();
                }
            }
            renderAjaxSuccess();
        }else{
            renderAjaxFailure("未选择消息！");
        }

    }

    public void delete(){
        String mids = getPara("mid");
        String[] smid = mids.split(",");
        if(!Strings.isNullOrEmpty(mids)) {
            for (String mid : smid) {
                Msgs msgs = Msgs.dao.findById(mid);
                msgs.deleteById(mid);
            }
            renderAjaxSuccess();
        }else {
            renderAjaxFailure("未选择要删除的消息！");
        }
    }
}
